package demo;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author ChinaManor
 * #Description T1
 * #Date: 24/6/2021 12:43
 */
public class T1 {
//    ## 使用JAVA或 Scala语言编程实现fink的 Word Count单词统计。
    public static void main(String[] args) throws Exception {
    //        新建文件为 words. txt,文件路径在/ export/ server/data下面,内容如下
//    Spark Flink flume hadoop
//    Flink spark flume hadoop

        //1.准备环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //2 准备数据-source
        DataStreamSource<String> inputStream = env.readTextFile("D:\\0615\\bigdata-flink\\datas\\wordcount.data");

        //3.处理数据-transformation
        SingleOutputStreamOperator<Tuple2<String, Integer>> resultStream = inputStream
                //分割单词
                .flatMap(new FlatMapFunction<String, String>() {
                    @Override
                    public void flatMap(String line, Collector<String> out) throws Exception {
                        for (String word : line.trim().split("\\s+")) {
                            out.collect(word);
                        }
                    }
                })
                // 转换二元组
                .map(new MapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> map(String word) throws Exception {
                        return new Tuple2<>(word, 1);
                    }
                })
                // 分组聚合
                .keyBy(0).sum(1);

        // 4 输出结果 sink
        resultStream.printToErr();

        // 5 触发执行 execute
        env.execute(T1.class.getSimpleName());

    }
}
